package com.fm.parser.zip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;

/**
 * @author leo.li
 */
public class DecompressionHandler implements ZipHandler {
    protected File directory;

    public DecompressionHandler(String directoryPath) {
        directory = new File(directoryPath);
        if (directory.exists()) {
            if (!directory.isDirectory()) {
                throw new RuntimeException(directoryPath + " already exsit but not a directory");
            }
        } else { // 不存在该目录
            if (!directory.mkdirs()) {
                throw new RuntimeException("create " + directoryPath + " fail");
            }
        }
    }

    @Override
    public void doEntry(ZipEntry entry, InputStream inputStream) throws IOException {
        File file = new File(directory.getAbsolutePath() + File.separatorChar + entry.getName());
        if (entry.isDirectory()) {
            if (!file.exists() && !file.mkdir()) {
                throw new RuntimeException("create " + file + " fail");
            }
        } else {
            if (file.exists()) {
                throw new RuntimeException("file " + file + " already exists");
            }
            if (!file.getParentFile().exists()) {
                if (!file.getParentFile().mkdirs()) {
                    throw new RuntimeException("file " + file.getParentFile() + " already exists");
                }
            }
            if (!file.createNewFile()) {
                throw new RuntimeException("create " + file + " fail");
            }
            try (FileOutputStream out = new FileOutputStream(file)) {
                byte[] bytes = new byte[1024];
                int count = 0;
                while ((count = inputStream.read(bytes)) != -1) {
                    out.write(bytes, 0, count);
                }
            }
        }
    }
}
